package demo2;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-07
 * Time: 10:17
 */
class MyTask2 implements Comparable<MyTask2>{
    private final Runnable runnable2;
    private final long time2;

    public MyTask2(Runnable runnable2,long delay2){
        this.runnable2 = runnable2;
        this.time2 = System.currentTimeMillis() + delay2;
    }

    @Override
    public int compareTo(MyTask2 o) {
        return (int)(this.time2 - o.time2);
    }

    public long getTime2() {
        return time2;
    }

    public void run2(){
        runnable2.run();
    }
}

class MyTime2{
    private final PriorityQueue<MyTask2> queue2 = new PriorityQueue<>();
    private final Object locker2 = new Object();
    public void schedule(Runnable runnable2,long delay2){
        //this就是myTime2
        synchronized (locker2) {
            MyTask2 myTask2 = new MyTask2(runnable2, delay2);
            queue2.offer(myTask2);
            this.notify();
        }
    }

    public MyTime2(){
        //this就是myTime2
        //阻塞
        //阻塞
        Thread thread2 = new Thread(() -> {
            while (true) {
                //this就是myTime2
                try {
                    synchronized (locker2) {
                        while (queue2.isEmpty()) {
                            //阻塞
                            this.wait();
                        }
                        MyTask2 myTask2 = queue2.peek();
                        long curTime2 = System.currentTimeMillis();
                        if (curTime2 >= myTask2.getTime2()) {
                            queue2.poll();
                            myTask2.run2();
                        } else {
                            //阻塞
                            this.wait(myTask2.getTime2() - curTime2);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread2.setDaemon(true);
        thread2.start();
    }
}

public class test2 {
    public static void main(String[] args) throws InterruptedException {
        MyTime2 myTime2 = new MyTime2();
        myTime2.schedule(()-> System.out.println(3000),3000);

        Thread.sleep(3500);
    }
}
